package middleware

import (
	"github.com/chicken-team-outside/chicken_transmission/proxy_server/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func rpcAuth(ctx *gin.Context) *model.TransportInfo {
	token := getTokenFormCtx(ctx)
	if token == "" {
		return nil
	}
	info, err := model.GetTransportInfoByTokenOrId(token, 0)
	if err != nil {
		zap.L().Warn("failed to get transport info by token", zap.Error(err), zap.String("token", token))
	}
	return info
}

func GetTransportInfo(ctx *gin.Context) *model.TransportInfo {
	value, exists := ctx.Get(RpcInfoKey)
	if !exists || value == nil {
		return nil
	}
	return value.(*model.TransportInfo)
}

func RpcAuthWare(ctx *gin.Context) {
	info := rpcAuth(ctx)
	if info != nil {
		if info.IsActive {
			ctx.Set(RpcInfoKey, info)
			ctx.Next()
		} else {
			ctx.AbortWithStatusJSON(200, gin.H{
				"code": 403,
				"msg":  "The token is forbidden!",
			})
		}
	} else {
		ctx.AbortWithStatusJSON(200, gin.H{
			"code": 403,
			"msg":  "invalid token!",
		})
	}
}
